package com.hbb20;


import io.michaelrocks.libphonenumber.ohos.AsYouTypeFormatter;
import io.michaelrocks.libphonenumber.ohos.LogUtils;
import io.michaelrocks.libphonenumber.ohos.PhoneNumberUtil;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.telephony.TelephoneNumberUtils;


public class InternationalPhoneTextWatcher implements Text.TextObserver {

    private static final String TAG = "Int'l Phone TextWatcher";
    PhoneNumberUtil phoneNumberUtil;

    private AsYouTypeFormatter mFormatter;
    //Editable lastFormatted = null;
    String lastFormatted = null;
    private int countryPhoneCode;


    private boolean internationalOnly;

    private TextField target;


    /**
     * @param context
     * @param countryNameCode  ISO 3166-1 two-letter country code that indicates the country/region
     *                         where the phone number is being entered.
     * @param countryPhoneCode Phone code of country. https://countrycode.org/
     */
    public InternationalPhoneTextWatcher(Context context, String countryNameCode, int countryPhoneCode) {
        this(context, countryNameCode, countryPhoneCode, true);
    }

    /**
     * @param context
     * @param countryNameCode   ISO 3166-1 two-letter country code that indicates the country/region
     *                          where the phone number is being entered.
     * @param countryPhoneCode  Phone code of country. https://countrycode.org/
     * @param internationalOnly Specifies whether numbers should only be formatted if they are
     *                          international vs national
     * @throws IllegalArgumentException IllegalArgumentException
     */
    public InternationalPhoneTextWatcher(Context context, String countryNameCode, int countryPhoneCode, boolean internationalOnly) {
        if (countryNameCode == null || countryNameCode.length() == 0)
            throw new IllegalArgumentException();
        phoneNumberUtil = PhoneNumberUtil.createInstance(context);
        updateCountry(countryNameCode, countryPhoneCode);
        this.internationalOnly = internationalOnly;
    }

    public void setTarget(TextField target) {
        this.target = target;
    }


    public void updateCountry(String countryNameCode, int countryPhoneCode) {
        this.countryPhoneCode = countryPhoneCode;
        mFormatter = phoneNumberUtil.getAsYouTypeFormatter(countryNameCode);
        mFormatter.clear();
        if (lastFormatted != null) {
            String onlyDigits = phoneNumberUtil.normalizeDigitsOnly(lastFormatted);
            // lastFormatted.replace(0, lastFormatted.length(), onlyDigits, 0, onlyDigits.length());
            lastFormatted = onlyDigits;
        }
    }



    @Override
    public void onTextUpdated(String s, int start, int before, int count) {
        stopFormatting();
        //无法设置 游标的位置
        String formatted = reformat(s);
        target.setText(formatted);
    }


    /**
     * this will format the number in international format (only).
     *
     * @param s s
     * @return String
     */
    private String reformat(CharSequence s) {

        String internationalFormatted = "";
        mFormatter.clear();
        char lastNonSeparator = 0;

        String countryCallingCode = "+" + countryPhoneCode;

        if (internationalOnly || (s.length() > 0 && s.charAt(0) != '0'))
            //to have number formatted as international format, add country code before that
            s = countryCallingCode + s;
        int len = s.length();

        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (TelephoneNumberUtils.isNotSeparator(c)) {
                if (lastNonSeparator != 0) {
                    internationalFormatted = mFormatter.inputDigit(lastNonSeparator);
                }
                lastNonSeparator = c;
            }
        }
        if (lastNonSeparator != 0) {
            internationalFormatted = mFormatter.inputDigit(lastNonSeparator);
        }

        internationalFormatted = internationalFormatted.trim();
        if (internationalOnly || (s.length() == 0 || s.charAt(0) != '0')) {
            if (internationalFormatted.length() > countryCallingCode.length()) {
                if (internationalFormatted.charAt(countryCallingCode.length()) == ' ')
                    internationalFormatted = internationalFormatted.substring(countryCallingCode.length() + 1);
                else
                    internationalFormatted = internationalFormatted.substring(countryCallingCode.length());
            } else {
                internationalFormatted = "";
            }
        }
        return TextTool.isNullOrEmpty(internationalFormatted) ? "" : internationalFormatted;
    }

    private void stopFormatting() {
        mFormatter.clear();
    }

    private boolean hasSeparator(final CharSequence s, final int start, final int count) {
        int end = Math.min(s.length(), start + count);
        for (int i = start; i < end; i++) {
            char c = s.charAt(i);
            if (!TelephoneNumberUtils.isNotSeparator(c)) {
                return true;
            }
        }
        return false;
    }


}
